package controllers.service;

import java.util.List;

import javax.persistence.EntityManager;

import enumerators.Tables;
import models.domain.Contract;
import models.domain.Customer;
import models.domain.User;
import models.persistence.JPAUtil;
import models.persistence.StaticQuerries;

public class CustomerService {

	private EntityManager em;

	public CustomerService() {
		em = JPAUtil.createEntityManager();
	}

	/**
	 * Returns true if found duplicate user
	 * 
	 * @param user
	 * @return
	 */
	public boolean checkDuplicateUserName(User user) {
		List<Customer> listCustomers = (List<Customer>) (Object) StaticQuerries
				.getAllItems(em, Tables.Customer);

		for (Customer customer : listCustomers) {
			if (customer.getUser().getUserName() == user.getUserName()) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Returns true if found duplicate user
	 * 
	 * @param customer
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean checkDuplicateCustomer(Customer customer) {
		List<Customer> listCustomers = (List<Customer>) (Object) StaticQuerries
				.getAllItems(em, Tables.Customer);
		if (listCustomers != null) {
			for (Customer customer2 : listCustomers) {
				if (customer2.getAFM() == customer.getAFM()
						|| customer2.getADT() == customer.getADT()) {
					return true;
				}
			}
		} else {
			return true;
		}

		return false;
	}

	/**
	 * Register Customer
	 * 
	 * @param customer
	 */
	public void registerCustomer(Customer customer) {
     
		em.persist(customer);
		
	}

	/**
	 * Validating correct customer Data returns false if success
	 * 
	 * @param customer
	 * @return
	 */
	public boolean validateData(String AFM, String E_mail) {

		if (!E_mail.contains("@") || !(AFM.length() == 9)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Registering new customer returning false on failure true on success
	 * 
	 * @param customer
	 * @return
	 */
	public boolean StartRegisterProcess(Customer customer) {
		if (checkDuplicateCustomer(customer)
				|| checkDuplicateUserName(customer.getUser())
				|| validateData(customer.getAFM(), customer.getE_mail())) {
			return false;
		} else {
			registerCustomer(customer);
			return true;
		}

	}

	/**
	 * Ανακτά όλα τα συμβόλαια που έχει ο πελάτης
	 * 
	 * @param contractId
	 * @return
	 */
	public List<Contract> getContracts(String username) {

		
		
		List<Contract> contracts = null;

		List<Customer> customers = em.createQuery(
				"select customers from " + Tables.Customer
						+ " customers where userName='" + username + "'")
				.getResultList();

		contracts = customers.get(0).getContracts();
		
		return contracts;
	}
	
	
	

}
